import { Button, Drawer, Form, FormInstance, Input, message, Switch } from "antd";
import FormItem from "antd/es/form/FormItem";
import React, { Dispatch, FC, MutableRefObject, RefObject, SetStateAction } from "react";
import { createSource, updateSource } from "src/api";
import ImgUpload, { ImgUploadRef } from "src/components/dataEntry/ImgUpload";
import { RoleRecord } from "../RoleType";

interface RoleInfoDrawer {
	visible: boolean;
	setVisible: Dispatch<SetStateAction<boolean>>;
	operationMode: "find" | "edit" | "add";
	onFinish: () => Promise<unknown>;
	operatedRecord: MutableRefObject<RoleRecord | null>;
	formRef: MutableRefObject<FormInstance | null>;
	uploadRef: RefObject<ImgUploadRef>;
}

const RoleInfoDrawer: FC<RoleInfoDrawer> = ({ visible, setVisible, operationMode, onFinish, operatedRecord, formRef, uploadRef }) => {
	const handleSubmit = () => {
		formRef.current?.validateFields().then(res => {
			if (operationMode === "add") {
				createSource({ ...res, source: "role", status: res.status ? 1 : 0 }).then(async () => {
					await onFinish();
					setVisible(false);
					message.success("添加成功");
					formRef.current?.resetFields();
				});
			}
			if (operationMode === "edit") {
				updateSource({ ...res, source: "role", status: res.status ? 1 : 0, id: operatedRecord.current?._id }).then(async () => {
					await onFinish();
					setVisible(false);
					message.success("编辑成功");
					formRef.current?.resetFields();
				});
			}
		});
	};
	return (
		<Drawer
			width={680}
			closable
			open={visible}
			onClose={() => setVisible(false)}
			extra={
				<div className="flex">
					<Button onClick={() => setVisible(false)}>取消</Button>
					<Button className="ml-2" type="primary" onClick={handleSubmit}>
						提交
					</Button>
				</div>
			}
		>
			<Form ref={formRef} labelCol={{ span: 3 }} wrapperCol={{ span: 18 }}>
				<FormItem name="name" label="角色名" rules={[{ required: true, message: "请输入角色" }]}>
					<Input placeholder="请输入角色名" />
				</FormItem>
				<FormItem name="description" label="角色描述" rules={[{ required: true, message: "请输入角色描述" }]}>
					<Input.TextArea rows={3} placeholder="请输入角色描述" />
				</FormItem>
				<FormItem name="avatar" label="角色头像">
					<ImgUpload ref={uploadRef} formRef={formRef} />
				</FormItem>
				<FormItem valuePropName="checked" name="status" label="状态">
					<Switch checkedChildren="启用" unCheckedChildren="禁用" />
				</FormItem>
			</Form>
		</Drawer>
	);
};

export default RoleInfoDrawer;
